package com.bit.lotterySystem.service.impl;

import com.bit.lotterySystem.common.errorcode.ServiceErrorCodeConstants;
import com.bit.lotterySystem.common.exception.ServiceException;
import com.bit.lotterySystem.common.utils.AliYuanSMSUtil;
import com.bit.lotterySystem.common.utils.CaptchaUtil;
import com.bit.lotterySystem.common.utils.RedisUtil;
import com.bit.lotterySystem.common.utils.RegexUtil;
import com.bit.lotterySystem.service.VerificationCodeService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

@Service
@Slf4j
public class VerificationCodeServiceImpl implements VerificationCodeService {
    private static final String VERIFICATION_CODE_PREFIX = "VERIFICATION_CODE_";
    //（分钟)验证码有效期
    private static final Long VERIFICATION_CODE_TIMEOUT = 5L;
    @Autowired
    private AliYuanSMSUtil smsUtil;
    @Autowired
    private RedisUtil redisUtil;

    @Override
    public void sendVerificationCode(String phoneNumber) {
        //校验手机号
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONENUMBER_ERROR);
        }
        //生成4位随机验证码
        String code = CaptchaUtil.getCaptcha(4);
        //发送验证码
        smsUtil.sendCode(phoneNumber, code, VERIFICATION_CODE_TIMEOUT);
        //缓存验证码
        redisUtil.set(VERIFICATION_CODE_PREFIX +phoneNumber,code,VERIFICATION_CODE_TIMEOUT);

    }

    @Override
    public String getVerificationCode(String phoneNumber) {
        if(!RegexUtil.checkMobile(phoneNumber)){
            throw new ServiceException(ServiceErrorCodeConstants.PHONENUMBER_ERROR);
        }
        return redisUtil.get(VERIFICATION_CODE_PREFIX + phoneNumber);
    }
}
